package flux;

import sagex.api.*;
import sagex.api.AiringAPI;

/**
 * 
 */

/**
 * @author Christopher M. Piper (fuzzy@weirdness.com)
 *
 */
public class Search {
	public Object[] search (String SearchString, Object[] SourceList){
		Object[] ResultsList = null;
		
		if (SourceList == null) {
			SourceList = MediaFileAPI.GetMediaFiles();
		}
		
		int Count = 0;
		for (Object SourceObject : SourceList)
			if (Eval(SourceObject, SearchString)) {
				ResultsList[Count] = SourceObject;
				Count = Count + 1;
			}
		return ResultsList;
	}
	
	private int FurtherOps (String SearchString) {
		int CharPos = 0;
		for (char Character : SearchString.toCharArray()) {
			CharPos = CharPos + 1;
			switch (Character) {
				case '&' : return CharPos;
				case '|' : return CharPos;
			}
		}
		return 0; 
	}

	private String Prefix(String SearchString){
		return SearchString.substring(0,FurtherOps(SearchString)-1).trim();
	}

	private String Suffix(String SearchString){
		return SearchString.substring(FurtherOps(SearchString+1)).trim();
	}
	
	private char Operator(String SearchString){
		return SearchString.charAt(FurtherOps(SearchString));
	}
	
	private boolean Eval(Object SourceObject, String SearchString) {
		boolean Result = false;
		if (FurtherOps(SearchString) == 0){
			if (SearchString.trim().equals("IsTV")) Result = MediaFileAPI.IsTVFile(SourceObject);
			if (SearchString.trim().equals("IsNotTV")) Result = !MediaFileAPI.IsTVFile(SourceObject);
			if (SearchString.trim().equals("IsWatched")) Result = AiringAPI.IsWatched(SourceObject);
			if (SearchString.trim().equals("IsNotWatched")) Result = !AiringAPI.IsWatched(SourceObject);
			if (SearchString.trim().equals("IsArchived")) Result = MediaFileAPI.IsLibraryFile(SourceObject);
			if (SearchString.trim().equals("IsNotArchived")) Result = !MediaFileAPI.IsLibraryFile(SourceObject);
			if (SearchString.trim().indexOf('=') > -1) {
				String Parameter = SearchString.substring(0,SearchString.indexOf('=')-1).trim();
				String Value = SearchString.substring(SearchString.indexOf('=')+1).trim().replace("'","");
				if (Parameter == "Category") {
					if (scrubString.GetShowCombCategories(SourceObject).indexOf(Value.replaceAll("!","")) > -1) {
						Result = true;
					}
					if (Value.indexOf('!')>-1) Result = !Result;
				}
				if (Parameter == "Tag") {
					String[] tags = mediaTag.GetMediaTags(SourceObject); 
					for (String tag : tags){
						if (tag == Value.replace("!","").trim()) {
							Result = true;
							break;
						}
					}
					if (Value.indexOf('!') > -1) Result = !Result;
				}
			}
		} else {
			if (Operator(SearchString) == '&') Result = Eval(SourceObject, Prefix(SearchString)) && Eval(SourceObject, Suffix(SearchString));
			if (Operator(SearchString)== '|') Result = Eval(SourceObject, Prefix(SearchString)) || Eval(SourceObject, Suffix(SearchString));
		}
		return Result;
	}
}
